//
//  InsetsLabel.swift
//  LearningLanguage
//
//  Created by Rui on 2023/10/14.
//

import UIKit

class InsetsLabel: UILabel {
    
    override var text: String? {
        didSet {
            setNeedsDisplay()
        }
    }
    
    // 设置内边距
    var contentEdgeInsets: UIEdgeInsets = .zero {
        didSet {
            setNeedsDisplay()
        }
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let horizontalInsets = contentEdgeInsets.left + contentEdgeInsets.right
        let verticalInsets = contentEdgeInsets.top + contentEdgeInsets.bottom
        
        let fitSize = CGSize(width: size.width - horizontalInsets, height: size.height - verticalInsets)
        var newSize = super.sizeThatFits(fitSize)
        newSize.width += horizontalInsets
        newSize.height += verticalInsets
        return newSize
    }
    
    override var intrinsicContentSize: CGSize {
        var maxWidth = self.preferredMaxLayoutWidth
        if maxWidth <= 0 {
            maxWidth = CGFloat.greatestFiniteMagnitude
        }
        return sizeThatFits(CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude))
    }
    
    override func drawText(in rect: CGRect) {
        var newRect = rect.inset(by: self.contentEdgeInsets)
        // 在某些情况下文字位置错误，因此做了如下保护
        // https://github.com/Tencent/QMUI_iOS/issues/529
        if self.numberOfLines == 1 && (self.lineBreakMode == .byWordWrapping || self.lineBreakMode == .byCharWrapping) {
            newRect = CGRectSetHeight(rect: rect, height: rect.size.height + self.contentEdgeInsets.top * 2)
        }
        super.drawText(in: newRect)
    }
    
    func CGRectSetHeight(rect: CGRect, height: CGFloat) -> CGRect {
        if (height < 0) {
            return rect
        }
        var newRect = rect
        newRect.size.height = flat(height)
        return newRect
    }
    
    func flat(_ floatValue: CGFloat) -> CGFloat {
        let removeFloatMin = floatValue == CGFloat.leastNormalMagnitude ? 0 : floatValue
        let scale = UIScreen.main.scale
        let flattedValue = ceil(removeFloatMin * scale) / scale
        return flattedValue
    }
    
}
